package com.hp.bon.sgw.wh.channel.handler;

import com.google.gson.Gson;
import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;
import com.hp.ocs.diameter.message.*;
import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


public class OutBlockUpHandle implements IAsynCallHandler {
    private static final Logger _log = LoggerFactory.getLogger(OutBlockUpHandle.class);
    private PrintStream printStream;
    private UserResourceConfigService userResourceConfigService ;
    private Map<String, Object> map;
    public OutBlockUpHandle(PrintStream printStream, Map<String, Object> map, XmlMessage reqXmlMessage) {
        this.printStream = printStream;
        this.map=map;
    }

    @Override
    public int getProtocolType() {
        return 0;
    }

    @Override
    public void onCallResult(CallParam callParam) {
        _log.info("=================http OutBlockUpHandle  onCallResult()" );
        long receiveTime = System.currentTimeMillis();
        XmlMessage ack = null;
        Object response = null;
        if (callParam.getResponse() != null) {
            response = callParam.getResponse();
        } else if (callParam.getRecvResponse() != null) {
            response = callParam.getRecvResponse();
        }
        if (response == null) {
            int _retcodeTmp = callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode();
            ack = SoapChannel.createERRAnwser(callParam.getSessionId(), _retcodeTmp, callParam.getResultMsg());
            callParam.setServiceResultCode(_retcodeTmp);// 11203
        } else {
            if (response instanceof Message) {// CCA -> XML
//                ack =BuzProcessorManager.getInstance().convertMessageToAck(callParam);
            } else if (response instanceof XmlMessage) {
                ack = (XmlMessage) response;
            } else {
                _log.warn("unknown response type:" + callParam.getResponse().getClass().getName());
            }
        }
        try {
            String respXML="";
            try {
                respXML = convertResponseString((Message)response, callParam,callParam.getServiceResultCode());
            }catch (Exception e) {
            }
            _log.info("===========respXML:" + respXML);
            XmlMessage ack1 = new XmlMessage(true);
            ack1.setMID(callParam.getSessionId());
            ack1.setREPTAG(0);
            ack1.setRTT(String.valueOf(receiveTime));
            ack1.setSIG(null);
            ack1.setRC("0");
            ack1.setDS("SUCCESS");
            ack1.setDATA(respXML);
            String respXMLa = convertResponseString(ack1);
            _log.info(respXMLa);
            byte[] resps = respXMLa.getBytes("UTF-8");
            ack1.setLength(resps.length);
            ack1.setMsgTime(System.currentTimeMillis());
            printStream.write(resps);
            printStream.close();


//            callParam.setResponse(ack);
//            if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库
//                MessageDetail detail = new MessageDetail();
//                detail.setBusinessCallId(callParam.getBussinessCallId());
//                detail.setSessionId(callParam.getSessionId());
//                detail.setServiceContextId(callParam.getServiceContextId());
//                detail.setMessageType(MessageType.WSA);
//                detail.setDetails(ack.getDATA());
//                detail.setMsgTime(new Date(ack.getMsgTime()));
//                detail.setOpType("send");
//                detail.setHostId(callParam.getUserName());
//                MessageDetailCacheManager.getInstance().add(detail);
//            }
//            TaskManager.taskProcess(callParam);
            _log.info("http response(onCallResult) " + respXML);
        } catch (UnsupportedEncodingException e) {
            _log.info("convertResponseString UnsupportedEncodingException error,msg=" + e.getMessage());
        } catch (IOException e) {
            _log.info("convertResponseString IOException,msg=" + e.getMessage());
        }
    }



    /**
     * 从Message中解析出需要的数据，并拼接成json字符串
     * @param answer
     * @param callParam
     * @param serviceResultCode
     * @return
     */
    private String convertResponseString(Message ack, CallParam callParam, int serviceResultCode) {
        _log.info("===========service_result_code===============" + serviceResultCode);

        String response = "";
        Map<String, Object> data = new HashMap<String, Object>();
        StringBuffer stringBuffer = null;
        String retCode="-1";
        String errMes="查询失败";
        Map<String, String> avpsFromMessage = getAvpsFromMessage(ack);
        _log.info("===========getAvpsFromMessage===============avpsFromMessage" + new Gson().toJson(avpsFromMessage));
        if(avpsFromMessage != null){
            retCode=avpsFromMessage.get("Result");
            errMes=avpsFromMessage.get("Para_Field_Result");
        }

        stringBuffer = new StringBuffer();
        stringBuffer.append("<Service_Information>");
        stringBuffer.append("<retCode>");
        stringBuffer.append(retCode);
        stringBuffer.append("</retCode>");
        stringBuffer.append("<errMsg>");
        stringBuffer.append(errMes);
        stringBuffer.append("</errMsg>");
        stringBuffer.append("</Service_Information>");

        //记录到BUSNIESS_RECORD_PORT表
//        LogBusniessRecordPort(ack, Integer.valueOf(retCode), errMes);
        //输出下游返回的信息
//        writeOutResponseMessage(Long.valueOf((String)map.get("receiveTime")), printStream, (XmlMessage)callParam.getRequest(), stringBuffer);
        return stringBuffer.toString();
    }

    /**
     * 处理CCA结果
     * @param answer
     * @return
     */
    public Map<String, String> getAvpsFromMessage(Message answer) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            AVP avp = answer.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION, Constants.DIAMETER_VENDOR_3GPP);
            AVP_Grouped avpServiceInfomation = new AVP_Grouped(avp);
            AVP[] avps = avpServiceInfomation.queryAVPs();
            for (AVP avpData : avps) {
                if (avpData.code() == 20631 && avpData.vendorID() == Constants.DIAMETER_VENDOR_CT) {
                    map.put("Result", String.valueOf(new AVP_Unsigned32(avpData).queryValue()));
                }
                if (avpData.code() == 80407 && avpData.vendorID() == Constants.DIAMETER_VENDOR_CT) {
                    map.put("Para_Field_Result", new AVP_UTF8String(avpData).queryValue());
                }
            }
        } catch (Exception e) {
            map = null;
            _log.info("getAvpsFromMessage Exception error,msg=" + e.getMessage());
        }
        return map;
    }

    private void writeOutResponseMessage(long receiveTime,
                                         PrintStream body,
                                         XmlMessage reqXmlMessage,
                                         StringBuffer stringBuffer){
        try {
            XmlMessage ack = new XmlMessage(true);
            ack.setMID(reqXmlMessage.getMID());
            ack.setREPTAG(0);
            ack.setRTT(String.valueOf(receiveTime));
            ack.setSIG(null);
            ack.setRC("0");
            ack.setDS("SUCCESS");
            ack.setDATA(stringBuffer.toString());
            String respXML = convertResponseString(ack);
            byte[] resps = respXML.getBytes("UTF-8");
            ack.setLength(resps.length);
            ack.setMsgTime(System.currentTimeMillis());
            body.write(resps);
            body.close();
        }catch (Exception e){

        }

    }
    // SOAP
    protected String convertResponseString(XmlMessage ack) {
        String orinData = ack.getDATA();
        String dataStr = (orinData == null || orinData.isEmpty()) ? orinData
                : "<![CDATA[" + orinData + "]]>";
        String errMsg = ack.getDS();
        _log.info("errMsg----:"+errMsg);
        errMsg = (errMsg != null) && (errMsg.indexOf('&') == -1)
                && (errMsg.indexOf('>') == -1) && (errMsg.indexOf('<') == -1) ? errMsg
                : StringEscapeUtils.escapeXml(errMsg);
        StringBuilder respXML = new StringBuilder();
        respXML.append("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><ns3:SgwQueryAck xmlns:ns3=\"http://www.chinatelecom.cn/SGW/SOAP\"><MID>");
        respXML.append(ack.getMID());
        respXML.append("</MID><REPTAG>0</REPTAG><RTT>");
        respXML.append(ack.getRTT());
        respXML.append("</RTT><SIG>");
        respXML.append(ack.getSIG());
        respXML.append("</SIG><RC>");
        respXML.append(ack.getRC());
        respXML.append("</RC><DS>");
        respXML.append(errMsg);
        respXML.append("</DS>");
        respXML.append("<DATA>");
        respXML.append(dataStr);
        respXML.append("</DATA></ns3:SgwQueryAck></SOAP-ENV:Body></SOAP-ENV:Envelope>");
        return respXML.toString();
    }
    public  static  void main(String [] srg){
    }
}
